from setuptools import setup, find_packages
import os
import sys
import subprocess


def configure_autostart():
    """配置程序开机自启动"""
    print("配置开机自启动...")

    if sys.platform == "win32":
        # Windows 系统
        try:
            # 获取当前用户启动文件夹路径
            startup_path = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs',
                                        'Startup')

            # 创建快捷方式
            exe_path = os.path.join(os.getcwd(), 'dist', 'WorkMonitor.exe')
            shortcut_path = os.path.join(startup_path, 'WorkMonitor.lnk')

            # 使用 PowerShell 创建快捷方式
            ps_script = f"""
            $WshShell = New-Object -ComObject WScript.Shell
            $Shortcut = $WshShell.CreateShortcut("{shortcut_path}")
            $Shortcut.TargetPath = "{exe_path}"
            $Shortcut.WorkingDirectory = "{os.path.dirname(exe_path)}"
            $Shortcut.Save()
            """

            # 执行 PowerShell 脚本
            subprocess.run(["powershell", "-Command", ps_script], check=True)

            print(f"✅ 已创建开机自启动快捷方式: {shortcut_path}")
            return True

        except Exception as e:
            print(f"❌ Windows 开机自启动配置失败: {e}")
            return False

    elif sys.platform == "linux":
        # Linux 系统
        try:
            # 创建 systemd 服务文件
            service_content = f"""[Unit]
Description=Work Monitor Service
After=network.target

[Service]
Type=simple
ExecStart={os.path.join(os.getcwd(), 'dist', 'WorkMonitor')}
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
"""

            service_path = "/etc/systemd/system/work-monitor.service"

            # 需要 root 权限写入
            with open(service_path, 'w') as f:
                f.write(service_content)

            # 启用服务
            subprocess.run(['sudo', 'systemctl', 'daemon-reload'], check=True)
            subprocess.run(['sudo', 'systemctl', 'enable', 'work-monitor.service'], check=True)

            print("✅ 已创建 systemd 服务并启用开机自启动")
            return True

        except Exception as e:
            print(f"❌ Linux 开机自启动配置失败: {e}")
            return False

    elif sys.platform == "darwin":
        # macOS 系统
        try:
            # 创建 LaunchAgent plist 文件
            plist_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.workmonitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>{os.path.join(os.getcwd(), 'dist', 'WorkMonitor')}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
"""

            plist_path = os.path.expanduser("~/Library/LaunchAgents/com.example.workmonitor.plist")

            with open(plist_path, 'w') as f:
                f.write(plist_content)

            print(f"✅ 已创建 LaunchAgent plist 文件: {plist_path}")
            return True

        except Exception as e:
            print(f"❌ macOS 开机自启动配置失败: {e}")
            return False

    else:
        print(f"❌ 不支持的操作系统: {sys.platform}")
        return False


setup(
    name="work-monitor",
    version="1.0.0",
    description="电脑工作量可视化桌面应用",
    author="Your Name",
    author_email="your.email@example.com",
    packages=find_packages(),
    install_requires=[
        "PySide6>=6.6.0",
        "pynput>=1.7.6",
        "psutil>=5.9.0",
        "pywin32>=306; sys_platform == 'win32'",
    ],
    entry_points={
        "console_scripts": [
            "work-monitor=main:main",
        ],
    },
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: End Users/Desktop",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
    ],
    python_requires=">=3.8",
    cmdclass={
        'install': lambda _: configure_autostart()
    }
)